<template>
  <div>
    <el-dialog
      :title="psorder_id+ '订单发货信息'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >
      <el-row>
        <el-col :span="16">
          <el-form v-loading="listLoading" :model="data" label-position="left" label-width="200px">
            <el-form-item label="采购账户">
              <el-select v-model="data.purchaseaccount_id" placeholder="采购账号" @change="handleChangePurchaseAccount">
                <el-option
                  v-for="item in this.purchase_accounts"
                  :key="item.id"
                  :label="item.username + '|' + item.name"
                  :value="item.id"
                />
              </el-select>
              <el-button icon="el-icon-setting" @click="handleManagePurchaseAccounts" />
            </el-form-item>
            <el-form-item label="销售额">
              <span>{{ total_sales }}</span>
              <el-alert
                v-if="total_sales > 0 && ((total_sales-data.cost)/total_sales) < 0.3"
                title="产品成本过高，可能亏损,请跟经理确认再录入"
                type="error"
                effect="dark"
              />
            </el-form-item>
            <el-form-item label="成本(包含运费)">
              <el-input v-model="data.cost" placeholder="请输入内容美金" @change="handleChangeCost">
                <template slot="prepend">美金:</template>
              </el-input>
            </el-form-item>
            <el-form-item label="采购订单ID">
              <el-input v-model="data.dropshipping_order_id" />
            </el-form-item>

            <el-form-item label="快递公司">
              <el-select v-model="shippingcompany_id" placeholder="选择快递公司" @change="handleGetCarriers">
                <el-option
                  v-for="item in this.shippingcomanys"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-button icon="el-icon-setting" @click="handleManageShippingCompany" />
            </el-form-item>
            <el-form-item v-if="shippingcompany_id !== ''" label="快递">
              <el-select v-model="data.shippingcarrier_id" placeholder="选择快递">
                <el-option
                  v-for="item in this.shippingcarriers"
                  :key="item.id"
                  :label="item.cnname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="data.shipping_company_order_id !== ''" label="快递公司系统单号">
              <el-input v-model="data.shipping_company_order_id" />
            </el-form-item>
            <el-form-item label="tracking_no">
              <el-input v-model="data.tracking_no" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <h3 style="margin: 0px">申报信息:</h3>
          <el-table :data="data.products" border fit highlight-current-row style="width: 100%">
            <el-table-column align="center" width="65px" prop="image" label="产品">
              <template slot-scope="scope">
                <img :src="scope.row.image" style="max-width: 50px; max-height: 50px">
              </template>
            </el-table-column>
            <el-table-column
              prop="declarePieces"
              label="数量"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.declarePieces" />
              </template>
            </el-table-column>

            <el-table-column
              prop="name"
              label="中文名称"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="Ename"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.Ename" />
              </template>
            </el-table-column>
            <el-table-column
              prop="UnitPrice"
              label="申报单价"
              width="80"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.UnitPrice" />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button type="danger" style="float: left" @click="confirm(true)">录入到快递公司</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm(false)">修改信息</el-button>
      </span>
    </el-dialog>
    <shippingcompany
      :shipping-company-visible="shippingCompanyVisible"
      @closeMyDialog="shippingCompanyVisible=false"
    />
    <purchaseaccounts
      :is-visible="pruchaseAccountVisible"
      @closeMyDialog="pruchaseAccountVisible=false"
    />
  </div>
</template>

<script>
import { Get as GetShippingCompany } from '@/api/orders/shippingcompany'
import { Get as GetCarriers } from '@/api/orders/shippingcarrier'
import { Get, Put, Post } from '@/api/orders/psordershipping'
import { Get as GetPurchaseAccounts } from '@/api/orders/purchaseaccounts'
import shippingcompany from '@/views/orders/element/shippingcompany'
import qs from 'qs'
import Cookies from 'js-cookie'
import store from '@/store'
import Purchaseaccounts from './purchaseaccounts'

export default {
  name: 'Shipping',
  components: { Purchaseaccounts, shippingcompany },
  props: ['shippingVisiable', 'psorder_id', 'total_sales'],
  data() {
    return {
      shippingCompanyVisible: false,
      pruchaseAccountVisible: false,
      purchase_accounts: [],
      purchaseaccount: '',
      myroles: [],
      listLoading: true,
      action: null,
      dialogVisible: false,
      title: '',
      accounts: [
        {
          label: '13dsfs@gmail.com[速卖通]',
          value: '13dsfs@gmail.com'
        },
        {
          label: '275911170@qq.com[速卖通]',
          value: '275911170@qq.com'
        },
        {
          label: 'sales@shinth.com[速卖通]',
          value: 'sales@shinth.com'
        },
        {
          label: 'taobao.com[taobao]',
          value: 'taobao.com'
        },
        {
          label: '1688.com[1688]',
          value: '1688.com'
        }
      ],
      data: {
        shippingcarrier_id: 1,
        cost: 0,
        tracking_no: '',
        dropshipping_account: '',
        purchaseaccount_id: '',
        dropshipping_order_id: '',
        name: '',
        psorder_id: ''
      },
      width: '',
      shippingcompany_id: '',
      shippingcomanys: [],
      shippingcarriers: [],
      innerDialogVisible: false
    }
  },
  watch: {
    shippingVisiable(v) {
      this.dialogVisible = v
      if (v) {
        this.GetShippingInfo()
        this.handleGetPurchaseAccounts()
      }
    }
  },
  created() {
    this.myroles = store.getters.roles
    this.data.purchaseaccount_id = Cookies.get('SHIPPING_DropShipping_Account_KEY')
    this.handleGetShipingCompany()
  },
  methods: {
    resetTemp() {
      this.data = {
        shippingcarrier_id: '',
        tracking_no: '',
        cost: 0,
        dropshipping_account: '',
        dropshipping_order_id: '',
        shipping_company_order_id: '',
        name: ''
      }
    },
    handleGetPurchaseAccounts() {
      GetPurchaseAccounts(null, null)
        .then(response => {
          this.purchase_accounts = response.data.data
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleRestoreCache() {
      // 先载入shipping company
      console.log('restore from cache')
      const account = Cookies.get('SHIPPING_DropShipping_Account_KEY')
      if (account !== undefined) {
        this.data.purchaseaccount_id = account
      }
      this.shippingcompany_id = Cookies.get('SHIPPING_Shippingcompany_id')
      console.log(this.shippingcompany_id)
      if (this.shippingcompany_id !== undefined) {
        this.shippingcompany_id = parseInt(this.shippingcompany_id)
        console.log('get shipping company id', this.shippingcompany_id)
        this.handleGetCarriers()
      } else {
        console.log('shipping company is undefind', this.shippingcompany_id)
        this.shippingcompany_id = ''
      }
    },
    handleGetShipingCompany() {
      this.resetTemp()
      GetShippingCompany(null, qs.stringify({
        kw: '',
        pagesize: 100,
        page: 1
      }))
        .then(response => {
          this.shippingcomanys = response.data.data
          if (this.shippingcomanys.length) {
            this.shippingcompany_id = this.shippingcomanys[0].id
            this.handleGetCarriers()
          }
        }).catch(err => {
          console.log(err)
        })
    },
    handleChangePurchaseAccount(v) {
      const account = this.purchase_accounts.filter(obj => {
        return obj.id === this.data.purchaseaccount_id
      })
      if (account.length > 0) {
        this.data.dropshipping_account = account[0].username
        console.log('change account:', this.data.dropshipping_account)
      }
    },
    handleGetCarriers() {
      GetCarriers(null, qs.stringify({
        shippingcompany_id: this.shippingcompany_id
      }))
        .then(response => {
          this.shippingcarriers = response.data.data
          let shippingcarrier_id = ''
          if (this.data.shippingcarrier_id === '' || this.data.shippingcarrier_id === undefined) {
            shippingcarrier_id = Cookies.get('SHIPPING_Shippingcarrier_id')
            if (shippingcarrier_id !== undefined) {
              shippingcarrier_id = parseInt(shippingcarrier_id)
            } else {
              shippingcarrier_id = ''
            }
          } else {
            shippingcarrier_id = this.data.shippingcarrier_id
          }
          // 检查是否在当前快递队列中
          console.log('get shipping carrtier id', shippingcarrier_id)
          let is_exist = false
          if (this.shippingcarriers.length > 0) {
            this.shippingcarriers.forEach(item => {
              if (item.id === shippingcarrier_id) {
                is_exist = true
              }
            })
            if (!is_exist) {
              shippingcarrier_id = this.shippingcarriers[0].id
              console.log('change carrier id', shippingcarrier_id)
            }
          }
          this.data.shippingcarrier_id = shippingcarrier_id
          console.log('shipp carrier id', this.data.shippingcarrier_id)
        })
        .catch(e => {
          console.log('error')
        })
    },
    handleManageShippingCompany() {
      this.shippingCompanyVisible = true
    },
    handleManagePurchaseAccounts() {
      this.pruchaseAccountVisible = true
    },
    GetShippingInfo() {
      this.listLoading = true
      this.resetTemp()
      Get(null, qs.stringify({
        kw: this.kwInput,
        psorder_id: this.psorder_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          if (response.data.total > 0) {
            this.data = response.data.data[0]
            this.shippingcompany_id = this.data.shippingcarrier__shippingcompany_id
            if (this.data['id'] === '') {
              this.handleRestoreCache()
            } else {
              this.handleGetCarriers()
            }

            delete this.data['shippingcarrier__shippingcompany_id']
          } else {
            this.handleRestoreCache()
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    /**
     * @return {boolean}
     */
    ValidOrderId(order_id) {
      console.log(order_id)
      if (this.data.purchaseaccount_id !== '') {
        const result = this.purchase_accounts.filter(obj => {
          return obj.id === this.data.purchaseaccount_id
        })
        console.log(result)
        if (result.length > 0 && result[0].name.indexOf('速卖通') !== -1) {
          if (order_id.length === 0) {
            return false
          } else {
            const ids = order_id.trim().split(/\s+/)
            for (let i = 0; i < ids.length; i++) {
              if (ids[i].length < 16) {
                return false
              }
            }
            return true
          }
        }
      }
      return true
    },
    handleChangeCost() {
      console.log('total_sales', this.total_sales)
      if (this.total_sales > 0 && ((this.total_sales - this.data.cost) / this.total_sales) < 0.3) {
        this.$notify({
          title: '警告',
          message: '采购价格过高，可能亏钱,请跟经理确认:' + this.data.cost,
          type: 'warning',
          duration: 1000
        })
      }
    },
    confirm(load_order) {
      if (!this.ValidOrderId(this.data.dropshipping_order_id)) {
        this.$notify({
          title: '错误',
          message: '订单ID不能为空或者少于16位',
          type: 'error',
          duration: 1000
        })
        return
      }

      if (this.data.cost <= 0 || this.data.cost > 10000) {
        this.$notify({
          title: '错误',
          message: '采购价格不合理请检查:' + this.data.cost,
          type: 'error',
          duration: 1000
        })
        return
      }

      let is_continue = false
      if (load_order && (this.data.shipping_company_order_id !== '')) {
        this.$confirm(`已经有第三方订单信息，确定还要继续录入吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          is_continue = true
        }).catch(() => {
          is_continue = false
        })
      } else {
        is_continue = true
      }
      if (is_continue === false) {
        return
      }
      this.data['load_order'] = load_order
      this.data.psorder_id = this.psorder_id
      if (this.data.id) {
        Cookies.set('SHIPPING_Shippingcarrier_id', this.data.shippingcarrier_id)
        Cookies.set('SHIPPING_Shippingcompany_id', this.shippingcompany_id)
        Cookies.set('SHIPPING_DropShipping_Account_KEY', this.data.purchaseaccount_id)
        Put(this.data.id, this.data
        ).then(response => {
          this.$emit('SetShippingSuccess', this.data)
          this.notify('修改成功')
          this.dialogVisible = false
        })
      } else {
        Post(this.data
        ).then(response => {
          this.$emit('SetShippingSuccess', this.data)
          this.notify('添加成功')
          this.dialogVisible = false
        })
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    close() {
      this.$emit('closeMyDialog', false)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-input {
  width: auto;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 5px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 5px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin: 10px auto !important;
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 60px;
  padding-top: 5px;
}

.top >>> .el-select {
  width: 300px;
}
</style>
